import { chain } from 'lodash'
import { EMPLOYEE_DATA_MAP } from '../enums'
import type { Employee } from '../types/employee'
import type { ExcelItem } from '@/module/attendanceManagement/types/attendance'
import { QAIndexDB } from '@/utils/indexDB'

export function transferEmployeeData(data: ExcelItem[]) {
  const checkColumnRes = employeeColumnsCheck(data)
  if (!checkColumnRes) {
    return false
  }
  return chain(data).drop().cloneDeep().map(transferEmployeeWithExcelData).value()
}

export function employeeColumnsCheck(data: ExcelItem[]) {
  const columnRow = data[0]
  return Object.keys(columnRow).every((columnIdx) => {
    return EMPLOYEE_DATA_MAP[columnIdx]?.keyDesc === columnRow[columnIdx]
  })
}

export function getEmployeeFieldWithColumn(key: string) {
  return chain(EMPLOYEE_DATA_MAP).find(item => item.key === key).value()?.columnName
}

export function transferEmployeeWithExcelData(data: ExcelItem): Employee {
  return {
    name: data[getEmployeeFieldWithColumn('name')],
    customerName: data[getEmployeeFieldWithColumn('customerName')],
    projectName: data[getEmployeeFieldWithColumn('projectName')],
    projectCode: data[getEmployeeFieldWithColumn('projectCode')],
    customerLevel: data[getEmployeeFieldWithColumn('customerLevel')],
    projectApprovalCode: data[getEmployeeFieldWithColumn('projectApprovalCode')],
  }
}

export async function getEmployee() {
  const res = await QAIndexDB.getItem<Employee[]>('EMPLOYEE')
  if (res) {
    return res
  }
}
